package com.LeeCode;

import java.util.ArrayList;
import java.util.List;

/**
 * 路径总和 II
 */

public class Code113 {
    public static void main(String[] args) {
        Integer[] arr = {5, 4, 8, 11, null, 13, 4, 7, 2, null, null, 5, 1};
        int targetSum = 22;
        TreeNode root = Utils.buildTree(arr);
        System.out.println(new Code113().pathSum(root, targetSum));
    }

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        dfs(root, targetSum, path, ans);
        return ans;
    }

    private void dfs(TreeNode root, int targetSum, List<Integer> path, List<List<Integer>> ans) {
        if (root == null) return;
        path.add(root.val);
        targetSum -= root.val;

        if (root.left == null && root.right == null && targetSum == 0) {
            ans.add(new ArrayList<>(path));
        } else {
            dfs(root.left, targetSum, path, ans);
            dfs(root.right, targetSum, path, ans);
        }
        path.remove(path.size() - 1);
    }
}
